package reone.android.anytest.getwindowTest;

import android.accessibilityservice.AccessibilityService;
import android.content.Intent;
import android.view.accessibility.AccessibilityEvent;
import android.view.accessibility.AccessibilityNodeInfo;

import java.util.List;

import reone.android.anytest.Util.LogUtil;

/**
 * Created by wangxingsheng on 16/6/17.
 */
public class WindowAccessibilitySeivice extends AccessibilityService {
    @Override
    public void onAccessibilityEvent(AccessibilityEvent event) {
        LogUtil.out("onAccessibilityEvent");
        AccessibilityNodeInfo root = getRootInActiveWindow();
        if(root == null)return;
        findAndPerformAction("G");
        LogUtil.out("getText",root.getText());
        LogUtil.out("getClassName",root.getClassName());
        LogUtil.out("getChildCount",root.getChildCount());
    }

    private void findAndPerformAction(String text)
    {
        AccessibilityNodeInfo root = getRootInActiveWindow();
        if(root == null)return;
        LogUtil.out("2getText",root.getText());
        LogUtil.out("2getClassName",root.getClassName());
        LogUtil.out("2getChildCount",root.getChildCount());
        // 查找当前窗口中包含“安装”文字的按钮
        if(getRootInActiveWindow()==null)
        return;
        //通过文字找到当前的节点
        List<AccessibilityNodeInfo> nodes = getRootInActiveWindow().findAccessibilityNodeInfosByText(text);
        for (int i = 0; i < nodes.size(); i++)
        {
            AccessibilityNodeInfo node = nodes.get(i);
            LogUtil.out("node.getClassName()",node.getClassName());
            // 执行按钮点击行为
            if (node.getClassName().equals("android.widget.Button")&&node.isEnabled())
            {
                node.performAction(AccessibilityNodeInfo.ACTION_CLICK);
            }
        }
    }

    @Override
    public void onInterrupt() {
        LogUtil.out("onInterrupt");
    }

    @Override
    protected void onServiceConnected() {
        super.onServiceConnected();
        LogUtil.out("onServiceConnected");
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        LogUtil.out("onStartCommand");
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onDestroy() {
        LogUtil.out("onDestroy");
        super.onDestroy();
    }

    @Override
    public void onCreate() {
        LogUtil.out("onCreate");
        super.onCreate();
    }
}
